package com.xudow.app.ui;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.home.HomePageMessageListMessage;
import com.activeshare.edu.ucenter.models.activity.ActivityWithAgency;
import com.activeshare.edu.ucenter.models.base.AdvInfo;
import com.activeshare.edu.ucenter.models.course.CourseDailyRecommendWithCourse;
import com.activeshare.edu.ucenter.models.home.HomePageMessageWithUserProfile;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.PushAgent;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.db.DatabaseHelper;
import com.xudow.app.db.dao.MessageDao;
import com.xudow.app.model.LocalMessage;
import com.xudow.app.model.SimpleUser;
import com.xudow.app.service.SessionService;
import com.xudow.app.ui.task.AdvertisementTask;
import com.xudow.app.ui.task.DailyRecommendCoursesTask;
import com.xudow.app.ui.task.HomeMessagesTask;
import com.xudow.app.ui.task.NewCourseCountTask;
import com.xudow.app.ui.task.UITopActivityTask;
import com.xudow.app.ui.task.UITopMessageTask;
import com.xudow.app.ui.widget.BadgeView;
import com.xudow.app.ui.widget.gallery.XViewPaper;
import com.xudow.app.util.AdvertisementUtils;
import com.xudow.app.util.DateUtil;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.Maps;
import com.xudow.app.util.MessageUtils;
import com.xudow.app.util.NetworkUtils;
import com.xudow.app.util.PrefUtils;
import com.xudow.app.util.StringUtils;
import com.xudow.app.util.UpdateManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * Main activity
 *
 * @author lukecheng
 */
public class MainActivity extends BaseActivity {
    private final static String TAG = makeLogTag(MainActivity.class);
    private final static int SCANNIN_GREQUEST_CODE = 1;
    private LayoutInflater inflater;
    private String scanner_result;//扫描结果（courseId）
    /**
     * 标示是否为按两次返回键退出
     */
    private static boolean isExitStatus = false;

    /**
     * 是不是打开应用后第一次获取消息
     */
    private boolean isFirstMessageLoad = true;

    /**
     * 广告图片
     */
    private XViewPaper xViewPaper;
    private LinearLayout ovalLayout;
    private List<View> listViews;
    private List<AdvInfo> advs;
    private RelativeLayout advLayout;

    private ScrollView scrollView;

    /**
     * 置顶消息
     */
    private LinearLayout uiTopMessageView;

    /**
     * 消息列表
     */
    private LinearLayout messageRecyclerView;

    private HomePageMessageListMessage homePageMessageListMessage; //包含timestamp的消息
    private List<LocalMessage> homeMessages;  //首页消息

    private HomeMessagesTask homeMessagesTask;
    private AdvertisementTask advertisementTask;
    private UITopMessageTask uiTopMessageTask;
    private UITopActivityTask uiTopActivityTask;
    private NewCourseCountTask newCourseCountTask;

    //每日课程推荐
    private XViewPaper xViewPaperDailyRecommend;
    private List<CourseDailyRecommendWithCourse> dailyRecommends;
    private RelativeLayout advLayoutDailyRecommend;
    private List<View> listViewsDailyRecommend;

    private DailyRecommendCoursesTask dailyRecommendCoursesTask;

    BadgeView badgeStudy, badgeQA, badgeEnroll, badgeMessage;

    /**
     * 置顶消息
     */
    private com.activeshare.edu.ucenter.models.msg.Message uiTopMsg;

    /**
     * 置顶活动
     */
    private ActivityWithAgency uiTopActivity;

    /**
     * 扫描点击
     */
    public void scannerClick(View view){
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, com.MipcaActivityCapture.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    scanner_result=bundle.getString("result");

                    getMyApp().makeToast(scanner_result.substring(3,scanner_result.length()));
                    // 课程详情页
                    Intent intent=new Intent(this,CourseDetailActivity.class);
                     String tag="";
                    if (scanner_result.startsWith("OA")) {
                        tag = "classid";
                        getMyApp().makeToast("OA");
                    }else if (scanner_result.startsWith("XD")){
                         tag="courseId";
                        getMyApp().makeToast("XD");
                    }
                    intent.putExtra(tag,Long.valueOf(scanner_result.substring(3,scanner_result.length())));
                    startActivity(intent);
                    //显示
                   // Bitmap bmp=(Bitmap) data.getParcelableExtra("bitmap");
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //广告
        xViewPaper = (XViewPaper) findViewById(R.id.gallery);
        ovalLayout = (LinearLayout) findViewById(R.id.vb);
        advLayout = (RelativeLayout) findViewById(R.id.ad);

        //每日课程推荐
        xViewPaperDailyRecommend = (XViewPaper) findViewById(R.id.course_ad_gallery);
        advLayoutDailyRecommend = (RelativeLayout) findViewById(R.id.course_ad);

        scrollView = (ScrollView) findViewById(R.id.scrollView);
        scrollView.setOnTouchListener(new HomeMessageScrollListener());

        uiTopMessageView = (LinearLayout) findViewById(R.id.top_message_list);
        messageRecyclerView = (LinearLayout) findViewById(R.id.message_list);

        inflater = LayoutInflater.from(this);

        homeMessages = new ArrayList<LocalMessage>();

        badgeStudy = new BadgeView(this, findViewById(R.id.study_badge));
        badgeQA = new BadgeView(this, findViewById(R.id.question_badge));
        badgeEnroll = new BadgeView(this, findViewById(R.id.enroll_badge));
        badgeMessage = new BadgeView(this, findViewById(R.id.message_badge));

        //检测更新
        if (NetworkUtils.isNetWorkConnected(this)) {
            // 检查新版本
            UpdateManager.getUpdateManager().checkAppUpdate(this, true);
        }

        //加载广告
        HashMap<String, String> advParam = Maps.newHashMap();
        advParam.put("app_page", "1");

        advertisementTask = new AdvertisementTask(this, advertisementTaskHandler);
        addTask(advertisementTask);
        advertisementTask.execute(advParam); // 获取首页顶部广告

        //加载每日课程推荐
        dailyRecommendCoursesTask = new DailyRecommendCoursesTask(this, dailyRecommendCoursesTaskHandler);
        addTask(dailyRecommendCoursesTask);
        dailyRecommendCoursesTask.execute(new HashMap<String, String>()); // 获取首页每日课程推荐

        loadHomeMessage(false); //加载首页消息

        startService(new Intent(this, SessionService.class)); // 开启服务 检查Session时候过期

        //开始定位
        listener = new NotifyLocationListener();
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(listener);
        mLocationClient.start();

        /**
         *友盟消息推送 start
         */
        if (PrefUtils.isPushEnable(this)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext());

                    XApplication application = (XApplication) getApplication();
                    if (application.isLogin()) {
                        SimpleUser user = PrefUtils.getUserInfo(getApplicationContext());

                        try {
                            mPushAgent.addAlias(user.getUsername(), Config.XUDOW_UMENG_MSG_ALIAS);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        mPushAgent.enable();
                    } else {
                        mPushAgent.enable();
                    }
                }
            }).start();
        }
        /**
         *友盟消息推送 end
         */
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!isFirstMessageLoad) {
            loadHomeMessage(true); // 加载首页消息
        }

        uiTopActivityTask = new UITopActivityTask(this, uiTopActivityTaskHandler);
        addTask(uiTopActivityTask);
        uiTopActivityTask.execute(new HashMap<String, String>()); // 获取活动

        uiTopMessageTask = new UITopMessageTask(this, uiTopMessageTaskHandler);
        addTask(uiTopMessageTask);
        uiTopMessageTask.execute(new HashMap<String, String>()); // 获取推荐消息

        HashMap<String, String> newCourseCountTaskParams = Maps.newHashMap();
        String timestamp = PrefUtils.getHomeMessageTimeStamp(this);

        if (!StringUtils.isEmpty(timestamp)) {
            Date timestampDate = DateUtil.strToDate(timestamp, DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            newCourseCountTaskParams.put("timestamp", "" + timestampDate.getTime());
        }
        newCourseCountTask = new NewCourseCountTask(this, newCourseCountTaskHandler);
        addTask(newCourseCountTask);
        newCourseCountTask.execute(newCourseCountTaskParams); // 获取新课程数目
    }

    /**
     * 从db加载消息
     *
     * @param userId
     * @param startTime 开始时间
     */
    private List<LocalMessage> loadMessagesFromDB(long userId, Date startTime) {
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase db = databaseHelper.getReadableDatabase();

        MessageDao messageDao = new MessageDao(db);
        List<LocalMessage> messagesInDB = messageDao.getMessages(userId, true, startTime);

        db.close();

        homeMessages.clear();
        homeMessages.addAll(messagesInDB);

        return messagesInDB;
    }

    /**
     * 加载首页消息
     *
     * @param isResume 是不是从onResume获取消息
     */
    private void loadHomeMessage(boolean isResume) {
        XApplication application = (XApplication) getApplication();

        if (application.isLogin() && !isResume) {
            //从数据库加载
            loadMessagesFromDB(application.getUserProfileId(), null);

            initMessageView();
        }

        //获取最新的消息
        HashMap<String, String> params = Maps.newHashMap();

        String timestamp = PrefUtils.getHomeMessageTimeStamp(this);

        if (!StringUtils.isEmpty(timestamp) && application.isLogin()) {
            params.put("timestamp", PrefUtils.getHomeMessageTimeStamp(this));
        }

        homeMessagesTask = new HomeMessagesTask(this, homeMessagesTaskHandler);
        addTask(homeMessagesTask);
        homeMessagesTask.execute(params); // 获取首页消息
    }

    /**
     * 首页消息Handler
     */
    private Handler homeMessagesTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (HomeMessagesTask.SUCCESS == msg.what) {
                isFirstMessageLoad = false;

                homePageMessageListMessage = (HomePageMessageListMessage)
                        msg.getData().getSerializable("homeMessage");

                PrefUtils.saveHomeMessageTimeStamp(MainActivity.this,
                        homePageMessageListMessage.getTimestamp());

                if (null == homePageMessageListMessage
                        || null == homePageMessageListMessage.getHomePageMessageList()
                        || homePageMessageListMessage.getHomePageMessageList().size() <= 0) {
                    return;
                }

                saveMessage(homePageMessageListMessage.getHomePageMessageList());
            }
        }
    };

    /**
     * 保存消息到db
     *
     * @param messages
     */
    private void saveMessage(List<HomePageMessageWithUserProfile> messages) {
        XApplication application = (XApplication) getApplication();

        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase db = databaseHelper.getWritableDatabase();

        List<LocalMessage> tmpMsgs = new ArrayList<LocalMessage>();

        MessageDao messageDao = new MessageDao(db);

        for (HomePageMessageWithUserProfile msg : messages) {
            LocalMessage localMessage = new LocalMessage();
            localMessage.setChannel(msg.getChannel());
            localMessage.setContent(msg.getContent());
            localMessage.setCreateTime(msg.getCreateTime());
            localMessage.setIsSystemMessage(msg.getIsSystemMessage());
            localMessage.setMessageId(msg.getId());
            localMessage.setStatus(msg.getStatus());
            localMessage.setTitle(msg.getTitle());
            localMessage.setUserId(application.getUserProfileId());
            localMessage.setMessageId(msg.getId());

            tmpMsgs.add(localMessage);

            messageDao.insertMessage(localMessage);
        }

        db.close();

        if (application.isLogin()) {
            //如果已经登录，从DB重新加载数据
            loadMessagesFromDB(application.getUserProfileId(), null);
            initMessageView();
        } else {
            //未登录直接显示消息
            homeMessages.clear();
            homeMessages.addAll(tmpMsgs);
            initMessageView();
        }
    }

    /**
     * 初始化消息列表
     */
    private void initMessageView() {
        messageRecyclerView.removeAllViews();

        for (LocalMessage msg : homeMessages) {
            messageRecyclerView.addView(createMessageView(msg));
        }
    }

    /**
     * 将消息添加到底部
     *
     * @param msgs
     */
    private void appendMessageView(List<LocalMessage> msgs) {
        for (LocalMessage msg : msgs) {
            messageRecyclerView.addView(createMessageView(msg));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exit();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 用户图标点击事件
     *
     * @param view
     */
    public void onUserClick(View view) {
        XApplication application = (XApplication) getApplication();

        if (application.isLogin()) { // 用户信息
            startActivity(new Intent(this, UserActivity.class));

        } else { // 登录
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    private void exit() {
        if (!isExitStatus) {
            isExitStatus = true;

            String exitPrompt = getString(R.string.common_exit_prompt);
            Toast.makeText(getApplicationContext(), exitPrompt, Toast.LENGTH_SHORT).show();

            exitKeydownHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
        }
    }

    /**
     * 是否是按两次返回键退出Handler
     */
    Handler exitKeydownHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExitStatus = false;
        }
    };

    /**
     * 设置广告图片
     */
    private void initViewPager() {
        listViews = new ArrayList<View>();

        for (int i = 0; i < advs.size(); i++) {
            final AdvInfo advInfo = advs.get(i);

            ImageView imageView = new ImageView(this);
            imageView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    AdvertisementUtils.open(MainActivity.this, advInfo); //根据广告类型打开不同界面
                }
            });

            String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, advInfo.getImgPath());
            LOGE("ZXJ", "imageUrl" + imageUrl);
            ImageUtils.loadImage(this, imageView, imageUrl, R.mipmap.empty);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            listViews.add(imageView);
        }

        xViewPaper.start(this, listViews, 4000, ovalLayout,
                R.layout.ad_bottom_item, R.id.ad_item_v,
                R.drawable.dot_focused, R.drawable.dot_normal);
    }

    /**
     * 获取消息icon
     *
     * @param msg
     * @return
     */
    private int getMessageIcon(LocalMessage msg) {
        //频道 1：我的学习 2：我要提问 3：我要报名 4：我的消息
        int res = R.mipmap.ico_msg_type_0;

        switch (msg.getChannel()) {
            case Config.MSG_CHANNEL_STUDY:
                res = R.mipmap.ico_msg_type_0;
                break;
            case Config.MSG_CHANNEL_QUESTION:
                res = R.mipmap.ico_msg_type_1;
                break;
            case Config.MSG_CHANNEL_ENROLL:
                res = R.mipmap.ico_msg_type_2;
                break;
            case Config.MSG_CHANNEL_MESSAGE:
                res = R.mipmap.ico_msg_type_3;
                break;
        }

        return res;
    }

    /**
     * 创建消息列表Item
     *
     * @param msg
     * @return
     */
    private LinearLayout createMessageView(final LocalMessage msg) {
        int res = getMessageIcon(msg);

        String time = MessageUtils.formatTimeStampString(this, msg.getCreateTime());

        LinearLayout view = (LinearLayout) inflater.inflate(R.layout.item_home_message_list, null);
        ((ImageView) view.findViewById(R.id.ico_msg_type)).setImageResource(res);
        ((TextView) view.findViewById(R.id.title)).setText(msg.getTitle());
        ((TextView) view.findViewById(R.id.time)).setText(time);

        if (null != msg.getContent()) {
            ((TextView) view.findViewById(R.id.summary)).setText(msg.getContent());
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewMessage(msg);
            }
        });

        return view;
    }

    /**
     * 消息查看
     *
     * @param msg
     */
    private void viewMessage(LocalMessage msg) {
        if (msg.getIsSystemMessage() == 1) {
            //系统消息
            Intent intent = new Intent(this, MessageViewActivity.class);
            intent.putExtra("messageId", msg.getMessageId());
            startActivity(intent);
        } else {
            //平文消息
            Intent intent = new Intent(this, TextMessageViewActivity.class);
            intent.putExtra("messageId", msg.getMessageId());
            intent.putExtra("content", msg.getContent());
            startActivity(intent);
        }
    }

    private HashMap<String, String> createEventMap(String key) {
        HashMap<String, String> map = Maps.newHashMap();
        map.put(key, "1");
        return map;
    }

    /**
     * 导航大块点击事件
     *
     * @param view
     */
    public void onNavItemClick(View view) {
        XApplication application = (XApplication) getApplication();

        final String EVENT_ID = "homePageModuleClicksCount";
        final String EVENT_1 = getString(R.string.study_title);
        final String EVENT_2 = getString(R.string.question_title);
        final String EVENT_3 = getString(R.string.enroll_title);
        final String EVENT_4 = getString(R.string.question_title);

        switch (view.getId()) {
            case R.id.enroll_item: // 优选课程
                MobclickAgent.onEvent(this, EVENT_ID, createEventMap(EVENT_3));
                startActivity(new Intent(this, CourseSearchActivity.class));
                break;
            case R.id.study_item: // 我的学习
                MobclickAgent.onEvent(this, EVENT_ID, createEventMap(EVENT_1));
                if (application.isLogin()) {
                    startActivity(new Intent(this, StudyActivity.class));
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.qanda_item: // 我要提问
                MobclickAgent.onEvent(this, EVENT_ID, createEventMap(EVENT_2));
                startActivity(new Intent(this, QandaActivity.class));
                break;
            case R.id.message_item: // 我的消息
                MobclickAgent.onEvent(this, EVENT_ID, createEventMap(EVENT_4));
                startActivity(new Intent(this, MessageActivity.class));
                break;
        }
    }

    /**
     * 右上角购物车按钮点击事件
     *
     * @param view
     */
    public void onSearchClick(View view) {
        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        }else{
            //TODO 进入购物车页面
            Intent intent=new Intent(this,CartActivity.class);
            startActivity(intent);
        }

    }

    /**
     * 首页消息滚动Listener
     */
    private class HomeMessageScrollListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    int scrollY = scrollView.getScrollY();
                    int height = scrollView.getHeight();
                    int scrollViewMeasuredHeight = scrollView.getChildAt(0).getMeasuredHeight();

                    if ((scrollY + height) == scrollViewMeasuredHeight) {
                        //移动到底部
                        XApplication application = (XApplication) getApplication();

                        if (null == homeMessages || homeMessages.size() <= 0) {
                            return false;
                        }

                        Date startTime = homeMessages.get(homeMessages.size() - 1).getCreateTime();
                        List<LocalMessage> messagesInDB = loadMessagesFromDB(application.getUserProfileId(), startTime);

                        appendMessageView(messagesInDB);
                    }
                    break;
                default:
                    break;
            }

            return false;
        }
    }

    /**
     * 广告加载Handler
     */
    private Handler advertisementTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (AdvertisementTask.SUCCESS == msg.what) {
                AdvInfo[] dataArr = (AdvInfo[]) msg.getData().getSerializable("advs");

                if (null == dataArr || dataArr.length <= 0) {
                    return;
                }

                advs = new ArrayList<AdvInfo>();
                advs.addAll(Arrays.asList(dataArr));

                initViewPager(); // 设置顶部广告图片

                advLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * 置顶消息Handler
     */
    private Handler uiTopMessageTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UITopMessageTask.SUCCESS == msg.what) {
                com.activeshare.edu.ucenter.models.msg.Message uiTopMsgTemp =
                        (com.activeshare.edu.ucenter.models.msg.Message) msg.getData().getSerializable("message");

                if (null != uiTopMsgTemp) {
                    uiTopMsg = uiTopMsgTemp;

                    initUITopMessage();
                }
            }
        }
    };

    /**
     * 置顶活动Handler
     */
    private Handler uiTopActivityTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UITopActivityTask.SUCCESS == msg.what) {
                ActivityWithAgency uiTopActivityTemp =
                        (ActivityWithAgency) msg.getData().getSerializable("activity");

                if (null != uiTopActivityTemp) {
                    uiTopActivity = uiTopActivityTemp;

                    initUITopMessage();
                }
            }
        }
    };

    /**
     * 创建置顶消息
     *
     * @param msg
     * @return
     */
    private LinearLayout createMessageUITopView(final com.activeshare.edu.ucenter.models.msg.Message msg) {
        int res = R.mipmap.ico_ui_top_msg;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.weight = 1;

        LinearLayout view = (LinearLayout) inflater.inflate(R.layout.item_home_message_ui_top, null);
        view.setLayoutParams(params);

        ((ImageView) view.findViewById(R.id.ico_msg_type)).setImageResource(res);
        ((TextView) view.findViewById(R.id.title)).setText(msg.getTitle());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //系统消息
                Intent intent = new Intent(MainActivity.this, MessageViewActivity.class);
                intent.putExtra("messageId", msg.getId());
                startActivity(intent);
            }
        });

        return view;
    }

    /**
     * 创建置顶活动
     *
     * @param msg
     * @return
     */
    private LinearLayout createActivityUITopView(final ActivityWithAgency msg) {
        int res = R.mipmap.ico_ui_top_activity;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.weight = 1;

        LinearLayout view = (LinearLayout) inflater.inflate(R.layout.item_home_message_ui_top, null);
        view.setLayoutParams(params);

        ((ImageView) view.findViewById(R.id.ico_msg_type)).setImageResource(res);
        ((TextView) view.findViewById(R.id.title)).setText(msg.getTitle());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ActivityViewActivity.class);
                intent.putExtra("activityId", msg.getId());
                intent.putExtra("activityPageUrl", msg.getActivityPageUrl());
                intent.putExtra("activityTitle", msg.getTitle());
                startActivity(intent);
            }
        });

        return view;
    }

    /**
     * 创建置顶信息
     */
    private void initUITopMessage() {
        uiTopMessageView.removeAllViews();

        if (null != uiTopActivity && null != uiTopMsg) {
            uiTopMessageView.addView(createActivityUITopView(uiTopActivity));

            View verticalDivider = new View(this);
            verticalDivider.setLayoutParams(new ViewGroup.LayoutParams(1,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            verticalDivider.setBackgroundResource(R.color.login_edit_border);
            uiTopMessageView.addView(verticalDivider);

            uiTopMessageView.addView(createMessageUITopView(uiTopMsg));
        }
    }

    private Handler newCourseCountTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (NewCourseCountTask.SUCCESS == msg.what) {
                long newCourseSize = msg.getData().getLong("newCourseSize", 0);

                if (newCourseSize > 0) {
                    badgeEnroll.setText(Long.toString(newCourseSize));
                    badgeEnroll.show();
                } else {
                    badgeEnroll.hide();
                }
            }
        }
    };

    /**
     * 定位开始
     */
    private LocationClient mLocationClient;
    private NotifyLocationListener listener;

    @Override
    protected void onStop() {
        super.onStop();

        mLocationClient = null;
        listener = null;
    }

    public class NotifyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            XApplication application = (XApplication) getApplication();
            application.latitude = location.getLatitude();
            application.longitude = location.getLongitude();
        }
    }
    /**
     * 定位结束
     */

    /**
     * 每日课程推荐Handler
     */
    private Handler dailyRecommendCoursesTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (DailyRecommendCoursesTask.SUCCESS == msg.what) {
                CourseDailyRecommendWithCourse[] dataArr =
                        (CourseDailyRecommendWithCourse[]) msg.getData().getSerializable("courses");

                if (null == dataArr || dataArr.length <= 0) {
                    return;
                }

                dailyRecommends = new ArrayList<CourseDailyRecommendWithCourse>();
                dailyRecommends.addAll(Arrays.asList(dataArr));

                initDailyRecommendViewPager();

                advLayoutDailyRecommend.setVisibility(View.VISIBLE);
            }
        }
    };

    /**
     * 设置广告图片
     */
    private void initDailyRecommendViewPager() {
        listViewsDailyRecommend = new ArrayList<View>();

        for (int i = 0; i < dailyRecommends.size(); i++) {
            final CourseDailyRecommendWithCourse courseRecommended = dailyRecommends.get(i);

            ImageView imageView = new ImageView(this);
            imageView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, CourseDetailActivity.class);
                    intent.putExtra("courseId", courseRecommended.getCourseId());
                    startActivity(intent);
                }
            });

            String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, courseRecommended.getImgPath());
            ImageUtils.loadImage(this, imageView, imageUrl, R.mipmap.empty);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            listViewsDailyRecommend.add(imageView);
        }

        xViewPaperDailyRecommend.start(this, listViewsDailyRecommend, 6000, null,
                R.layout.ad_bottom_item, R.id.ad_item_v,
                R.drawable.dot_focused, R.drawable.dot_normal);
    }

}
